/* The dialog.js is independent and need polish some how later */
/* The implementation need some convention in html design, so just internal use only */
/* The implementation does not use css path to find elements, it depends on the function getElementById */

/* Current Is The Main Object That We Provide For All Of Our Pages */
var lh_g;
var pos_g;
var slist_g = [];
var index_g;

var zoyoe = new function(){
  this.debug = false;
  this.InitZoyoe = function(dbg,yui,static_dialog){
    this.debug = dbg;
    this.ui = new ZOYOE_UI(this,yui,static_dialog);
  }
  /* Dialog Related Global Variables */
  this.comps = {};
  this.map = null;
  this.week_day = new function(){
    this.Monday=0;
    this.Tuesday=1;
    this.Wednesday=2;
    this.Thursday=3;
    this.Friday=4;
    this.Saturday=5;
    this.Sunday=6;
  }
  this.ALERT = function(str){
    if (this.debug){
      alert(str);
    }
  }
  this.Redirect =function(url){
    window.location.href = url;
  }
  this.TimeStamp = function(){
    var tstamp = "";
    return (new Date()).getTime();
  }
  this.Update = function(update){
    var self = this;
    var config = {
        method: 'GET'
    }
    YUI().use("io-form",function(Y){
      function complete(id,o,args){
        zoyoe.ALERT(o.responseText);
        document.getElementById(args[0]).parentNode.innerHTML = o.responseText;
      }
      Y.on('io:complete',complete,Y,[update.comp_id]);
      var request = Y.io(update.uri,config);
    });
  }
  this.ShowShortCut = function(lh,pos,slist,index){
    // alert("show short cut !!!!");
    lh_g = lh;
    pos_g = pos;
    slist_g = slist;
    index_g = index;
    if(slist.length!=0){
      // alert("enter if ...........");
      var float_info = document.getElementById('float-info');
      float_info.rotate = 0;
      //var ele = document.getElementsByTagName('body')[0];

      // var width = ele.offsetWidth;
      // var height = ele.offsetHeight;
      // var top = (height - 350)/2;
      // var left = (width - 500)/2;

      var tmpPageSize = GetPageSize().split(",");
      var width = parseInt(tmpPageSize[0]);
      var height = parseInt(tmpPageSize[1]);
      var left = (width - 500)/2 + 200;

      /* by mike  */
      var iphone = document.getElementById('iphone-warpper');
      if (iphone) {
        var top = 200;  
        left = 210;
      }else{
        var top = (height - 350)/2;  
      }


      /* Using interpolation here */
      float_info.style.left = this.n2px(left);
      float_info.style.top = this.n2px(top);

      if(true || this.ui.content_active){
        // alert("show display here 。。。。。。");
        this.ui.HibernateContent();
        var count = 1;
        var serv = null;

        YUI().use('node',function(yui_node){
          // alert("node ?");
          // only support one shortcut, need to improve the function later
          serv = slist[index];
          var name = serv.name;
          var img_src = "/gallery/imageicon/" + name + "/icon/?sc=mid";
          var img_cont = yui_node.one("#float-info-service-img div");
          if (img_cont != null) {
            img_cont.set('innerHTML',"<a class='img' href='/core/service/" + name + "/'><img src = '" + img_src +"' ></img></a>");
          }

          serv = slist[index];
          //yui_node.one("#float-info .name").set('innerHTML',serv.name.replace(/-/g, ' '));
          //yui_node.one("#float-info .name").set('href', "/core/service/" + name + "/");
          yui_node.one("#float-info .type").set('innerHTML',serv.type);

          yui_node.one("#float-info .phone").set('innerHTML',phoneformat(serv.phone));
          yui_node.one("#float-info .address").set('innerHTML',serv.address);
          yui_node.one("#float-info .description").set('innerHTML',serv.description);
          yui_node.one("#float-info .nest span").set('innerHTML',slist.length);
          yui_node.one("#float-info .slist-length span").set('innerHTML', slist_g.length);
          //yui_node.one("#float-info .type span").set('innerHTML',serv.type);
          yui_node.one("#float-info .index span").set('innerHTML', index_g+1 + '&nbsp/&nbsp');
          var float_sh = yui_node.one('#float-info .div-scroll div.hscroll');

          float_info.style.display = "block";
        });
        
        /** commented by mike 
        alert("zoom deal");
        var zoom = zoyoe.map.GetZoom() + 3; */ /* Keep Trying */
        /*
        if(zoom >17){zoom = 17;}
        var smap = new MapInfoCore(function(rmap){
          alert("action");
          for(s in slist){
            rmap.AddService(slist[s]);
          }
          rmap.ShiftZoom(true);
        },lh,"float-info-location",zoom,true);
        */

      }
    }else{
    }
  }


  this.CloseShortCut = function(){
    var float_info = document.getElementById('float-info');
    float_info.style.display = "none";
    try{
      this.ui.ActivateContent();  
    }catch(err){
      //TypeError: Cannot call method 'ActivateContent' of undefined
    }
  }
  this.ShowNextShortCut = function(){
    length = slist_g.length;
    if (index_g == length-1) {
      index_g = 0;
    }else{
      index_g++;
    }
    this.CloseShortCut();
    this.ShowShortCut(lh_g, pos_g, slist_g, index_g);
  }
  this.ShowPreviousShortCut = function(){
    length = slist_g.length;
    if (index_g == 0) {
      index_g = length-1;
    }else{
      index_g--;
    }
    this.CloseShortCut();
    this.ShowShortCut(lh_g, pos_g, slist_g, index_g);
  }
  this.n2px = function(n){
    return n+'px';
  }
  this.px2n = function(px){
    return parseInt(px);
  }
  this.ArrangeClips = function(id,tmpid){
    YUI().use('node',function(yui_node){
      var container = yui_node.one("#"+id);
      var src_group = yui_node.one("#"+tmpid);
      container.set('innerHTML','');
      var step_width = 220; //changed from 240 to 230, then 3 items per line would change to 4 items a line.
      var width = zoyoe.px2n(container.getComputedStyle("width"));
      var src_parent = yui_node.Node.getDOMNode(src_group);
      var number = Math.floor((width - 10)/step_width);
      var vlanes = [];
      for(var i=0;i<number;i++){
        var vlane = yui_node.Node.create("<div class='vlane'></div>");
        vlanes.push(vlane);
        container.append(vlane);
      }
      if (src_parent != null && src_parent.firstChild != null) {
        for(var n = src_parent.firstChild;n;n=n.nextSibling){
          if(n.nodeName != "#text"){
            var tmp = vlanes[0];
            var j = 0;
            for(var i = 0;i<vlanes.length;i++){
              var domele = yui_node.Node.getDOMNode(vlanes[i]);
              var t = yui_node.Node.getDOMNode(tmp);
              if(domele.offsetHeight < t.offsetHeight){
                tmp = vlanes[i]; 
              }
            }
            tmp.append((yui_node.one(n)).cloneNode(true));
          }
        }
      }
      if (src_group != null) {
        src_group.set('innerHTML','');
      }
    });
  }
}

  
/* The following function need YUI3 to succeed */

var config = new function(){
   this.choice = new Array();
   this.choice.push(new function(){
     this.name = 'sort-select';
     this.handler = function(type){
     }
   });
   this.combo = new Array();
   this.combo.push(new function(){
     this.name = "working-days";
     this.handler = function(type){
       zoyoe.map.ToggleWorkingDayFilter(type);
     }
   });
   this.combo.push(new function(){
     this.name = "type-select";
     this.handler = function(type){
       zoyoe.map.ToggleTypeFilter(type);
     }
   });
}

function InitChoiceControl(setting){ 
   YUI().use('node',function(node){
     var values = node.all('#'+ setting.name + " a");
     values.on('click', function(e){
        values.removeClass('selected');
        e.currentTarget.addClass('selected');
        setting.handler(node.Node.getDOMNode(e.currentTarget.one('span')).nextSibling.data);
      });
   });
}

function InitComboControl(setting){ 
   YUI().use('node',function(node){
     var values = node.all('#'+ setting.name + " a");
     values.on('click', function(e){
        if(e.currentTarget.hasClass('selected')){
          e.currentTarget.removeClass('selected');
        }else{
          e.currentTarget.addClass('selected');
        }
        setting.handler(node.Node.getDOMNode(e.currentTarget.one('span')).nextSibling.data);
      });
   });
}

function InitSurburbList(){
  YUI().use('node',function(node){
    var input = node.one('#report-bar .extension-auto-complete input');
    var dom_input = node.Node.getDOMNode(input);
    dom_input.ext_onchange = function(searchStr){
      if(zoyoe.map){
         zoyoe.map.TargetPlace(searchStr,"AutoCompJSON");
      } else {
         zoyoe.ALERT("Map not loaded");
      }
    }
  });
}

function InitControlPanel(){
  YUI().use('dd-plugin', function(Y){
      var node = Y.one('#config-bar');
      node.plug(Y.Plugin.Drag);
      node.dd.addHandle('div.window-title');
  });
  for(var i=0;i<config.choice.length;i++){
    InitChoiceControl(config.choice[i]);
  }
  for(var i=0;i<config.combo.length;i++){
    InitComboControl(config.combo[i]);
  }
  InitSurburbList();
}


function RemoveFromArray(list,ele){
   var i = 0;
   for(;i<list.length;i++){
     if(list[i] == ele){
        break;
     }
   }
   if(i<list.length){
      list.splice(i,1);
   }
}


/* Useful functions */
foreach = function(list,fun){
  var len = list.length;
  if (typeof fun != "function"){
    throw new TypeError();
  }
  var thisp = arguments[1];
  for (var i = 0; i < len; i++){
    if (i in list){
      fun.call(thisp, list[i], i, list);
    }
  }
};
function is_int(value){ 
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else { 
      return false;
  } 
}
function GetPageSize() {
  var scrW, scrH;
  if(window.innerHeight && window.scrollMaxY) {
    // Mozilla
    scrW = window.innerWidth + window.scrollMaxX;
    scrH = window.innerHeight + window.scrollMaxY;
  } else if(document.body.scrollHeight > document.body.offsetHeight){
    // all but IE Mac
    scrW = document.body.scrollWidth;
    scrH = document.body.scrollHeight;
  } else if(document.body) { // IE Mac
    scrW = document.body.offsetWidth;
    scrH = document.body.offsetHeight;
  }

  var winW, winH;
  if(window.innerHeight) { // all except IE
    winW = window.innerWidth;
    winH = window.innerHeight;
  } else if (document.documentElement 
    && document.documentElement.clientHeight) {
    // IE 6 Strict Mode
    winW = document.documentElement.clientWidth; 
    winH = document.documentElement.clientHeight;
  } else if (document.body) { // other
    winW = document.body.clientWidth;
    winH = document.body.clientHeight;
  }

  // for small pages with total size less then the viewport
  var pageW = (scrW<winW) ? winW : scrW;
  var pageH = (scrH<winH) ? winH : scrH;

  return pageW + "," + pageH;
}

function phoneformat(s){
  if(s.length == 10){
    if(s.substr(0,2)=="04"){
      return s.substr(0,4) + " " + s.substr(4,3) + " " + s.substr(7,3);
    }else{
      return s.substr(0,2) + " " + s.substr(2,4) + " " + s.substr(6,4);
    }
  }else{
    return s;
  }
}